package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
 * <p>
 * ${table.comment!} 服务实现类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {

}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {

    @Override
    public void saveData(${entity} ${entity}){
        String childs = "${table.controllerName}";
        List<String> strings = Arrays.asList(childs.split(","));
        extracted(${entity}, strings, null);
    }

private  void extracted(Object clazz, List<String> strings, Long id) {
    //获取service
    Object bean = SpringUtil.getBean(StrUtil.lowerFirst(clazz.getClass().getSimpleName())+"ServiceImpl");
    //获取service的保存方法
    Method save = ReflectionUtils.findMethod(bean.getClass(), "save", Object.class);
    //获取clazz的setParentid方法
    Method setParentid = ReflectionUtils.findMethod(clazz.getClass(), "setParentid", Long.class);
    //反射执行setParentid
    ReflectionUtils.invokeMethod(setParentid, clazz, new Object[]{id});
    //执行保存方法
    ReflectionUtils.invokeMethod(save, bean, clazz);
    //获取clazz的所有字段信息
    List<Field> fields = Arrays.asList(clazz.getClass().getDeclaredFields());
    //字段信息转为map
    Map<String, Field> collects = fields.stream().collect(Collectors.toMap(Field::getName, Function.identity()));
        //遍历对象类型
    strings.forEach(x->{
        if(collects.get(x)!=null){
            if(collects.get(x).getType().equals(List.class)){
                List<Object> valueList = (List<Object>) ReflectUtil.getFieldValue(clazz,x);
                for (Object o: valueList) {
                    extracted(o,strings,(Long) ReflectUtil.getFieldValue(clazz,"id"));
                }
            }else {
                Object fieldsValue = ReflectUtil.getFieldValue(clazz,x);
                extracted(fieldsValue,strings,(Long) ReflectUtil.getFieldValue(clazz,"id"));
            }
        }
    });
}
}
</#if>
